游戏设计者模式(未待完续)

游戏设计者模式

time:2026_1_21

单例模式

通常用于游戏中的全局管理类,保证整个程序(进程)中只有一个实例对象存在。只有第一次调用会进行初始化,后面调用保持原始状态。

1
2
3
4
5
6
7
8
9
10
11
class Game{
public:
static Game *getgame(){
if(game == nullptr){
game = new(Game);
}
return game;
}
private:
static Game *game
}

模板模式

把共同的部分集中到一个基类,把不同的细节部分留给子类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Character{
protected:
virtual void drow();
virtual void move();
public:
void updata(){
move();
move();
move();
drow();
}
};
struct Game{
vector<character *> chars;
void updata(){
for(auto && c : chars){
c->updata();
}
}
}

状态模式

为了解决枚举问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
struct Monster;

struct State {
virtual void update(Monster *monster) = 0;
};

struct Idle : State {
void update(Monster *monster) override {
if (monster->seesPlayer()) {
monster->setState(new Chase());
}
}
};

struct Chase : State {
void update(Monster *monster) override {
if (monster->canAttack()) {
monster->setState(new Attack());
} else if (!monster->seesPlayer()) {
monster->setState(new Idle());
}
}
};

struct Attack : State {
void update(Monster *monster) override {
if (!monster->seesPlayer()) {
monster->setState(new Idle());
}
}
};

struct Monster {
State *state = new Idle();

void update() {
state->update(this);
}

void setState(State *newState) {
delete state;
state = newState;
}
};

原型模式

主要解决问题时深拷贝的问题,因为在虚函数会导致的拷贝构造函数会出现拷贝不完全的情况,所以要采用原型模型进行完整数据类型拷贝

1
2
3
// 视线深拷贝
Ball *ball = new RedBall();
Ball *newball = new BedBall(*dynamic_cast<RedBall *>(ball));

原型模式将对象的拷贝方法作为虚函数,返回一个虚接口的指针,避免了直接拷贝类型。但虚函数内部会调用子类真正的构造函数,实现深拷贝。

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Ball{
virtual thread_ptr(Ball) *close() = 0;//加入thread_ptr 实现内存智能管理
};

struct RedBall :Ball{
thread_ptr(Ball) *close() override{
return new RedBall(*this);
}
int x ;// 如果有成员变量,也会一并被拷贝到
}

Ball *ball = new RedBall();
Ball *ball_2 = ball->close(); //视线深拷贝,

CRTP 模式自动实现 clone CRTP能将子类加入模版中已放置重复定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct Ball {
virtual unique_ptr<Ball> clone() = 0;
};

template <class Derived>
struct BallImpl : Ball { // 自动实现 clone 的辅助工具类
unique_ptr<Ball> clone() override {
Derived *that = static_cast<Derived *>(this);
return make_unique<Derived>(*that);
}
};

struct RedBall : BallImpl<RedBall> {
// unique_ptr<Ball> clone() override { // BallImpl 自动实现的 clone 等价于
// return make_unique<RedBall>(*this); // 调用 RedBall 的拷贝构造函数
// }
};

struct BlueBall : BallImpl<BlueBall> {
// unique_ptr<Ball> clone() override { // BallImpl 自动实现的 clone 等价于
// return make_unique<BlueBall>(*this); // 调用 BlueBall 的拷贝构造函数
// }
};


Ball *ball = new RedBall();
Ball *ball_2 = ball->close(); //视线深拷贝,

组件模式

1
2
3
4
struct connect{
virtual void updata()
}

观察者模式

发布-订阅模式

访问者模式